package com.cysion.study.ui

import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.view.View
import com.cysion.other.color
import com.cysion.study.R
import com.cysion.study.adapter.DayCourseAdapter
import com.cysion.study.entity.CourseDayEntity
import com.cysion.study.helper.UserCache
import com.cysion.study.ktbox.Box
import com.cysion.study.ktbox.base.BaseActivity
import com.cysion.study.ktbox.base.ITEM_CLICK
import com.cysion.study.ktbox.net.BaseResponseRx
import com.cysion.study.ktbox.net.ErrorHandler
import com.cysion.study.ktbox.utils.ACache
import com.cysion.study.ktbox.utils.darkTextTheme
import com.cysion.study.net.ApiClient
import com.cysion.study.net.Urls
import com.cysion.study.ui.personal.ActivityDetailActivity
import com.cysion.study.ui.personal.ClassDetailActivity
import com.cysion.study.ui.personal.HostingDetailActivity
import com.cysion.study.ui.personal.StudiesDetailActivity
import com.cysion.study.uibox.bar.TopBar
import com.cysion.study.uibox.dialog.Alert
import com.cysion.study.widget.JsonMap
import com.cysion.study.widget.ShowToast
import com.cysion.study.widget.UIHelper
import com.cysion.study.widget.http.HttpUtil
import com.cysion.targetfun._subscribe
import com.haibin.calendarview.Calendar
import com.haibin.calendarview.CalendarView
import com.loopj.android.http.JsonHttpResponseHandler
import com.loopj.android.http.RequestParams
import com.scwang.smartrefresh.layout.constant.RefreshState
import kotlinx.android.synthetic.main.activity_course_day.*
import org.json.JSONObject
import java.text.SimpleDateFormat
import java.util.*


//我的课表
class DayCourseMoreActivity : BaseActivity(), CalendarView.OnCalendarSelectListener,
    View.OnClickListener {


    override fun getLayoutId(): Int = R.layout.activity_course_day
    private var mYear: Int = 0

    override fun initView() {
        darkTextTheme(color(R.color.white))
        topbar.apply {
            setTitle("我的课表")
            setOnTopBarClickListener { obj, pos ->
                if (pos == TopBar.Pos.LEFT) {
                    finish()
                }
            }
        }

        //日历相关
        mYear = mCalendarView.getCurYear()
        mCalendarView.setOnCalendarSelectListener(this)

        initRefreshLayout()
        initRecyclerView()
    }

    //加载数据
    override fun initData() {
        super.initData()
        smartLayout.autoRefresh()
    }

    private lateinit var proAdapter: DayCourseAdapter
    //    初始化刷新控件
    private fun initRefreshLayout() {
        smartLayout.setOnRefreshListener {
            requestData()
            smartLayout.setEnableLoadMore(false)
        }
        smartLayout.setOnLoadMoreListener {
            //            getDataList()
            smartLayout.setEnableLoadMore(false)
        }
    }

    //初始化列表
    private fun initRecyclerView() {
        rv_list.isNestedScrollingEnabled = false
        proAdapter = DayCourseAdapter(dataList, Box.context)
        rv_list.adapter = proAdapter
        rv_list.layoutManager = LinearLayoutManager(Box.context)

        proAdapter.setOnTypeClickListener { obj, position, flag ->
            if (flag == ITEM_CLICK) {
                //type: :0//类型 0.托管课程 1.课程 2.活动安排 3.研学安排
                if (dataList[position].type == "0") {//托管
                    var bundle = Bundle()
                    bundle.putString("courseId",obj.id)
                    bundle.putString("classId",obj.cid)
                    //托管详情
                    UIHelper.jump(this, HostingDetailActivity::class.java,bundle)
                } else if (dataList[position].type == "1") {//课程
                    var bundle = Bundle()
                    bundle.putString("courseId",obj.id)//课时id
                    UIHelper.jump(this, ClassDetailActivity::class.java,bundle)//课程详情
                } else if (dataList[position].type == "2") {//活动
                    var bundle = Bundle()
                    bundle.putString("id",obj.id)//
                    bundle.putString("cid",obj.cid)//
                    bundle.putString("activityName",obj.name)//
                    //活动详情
                    UIHelper.jump(this, ActivityDetailActivity::class.java,bundle)

                } else if (dataList[position].type == "3") {//研学
                    var bundle = Bundle()
                    bundle.putString("courseId",obj.id)//日程id
                    bundle.putString("classId",obj.cid)//班级id
                    UIHelper.jump(this, StudiesDetailActivity::class.java,bundle)
                }

            }
        }

        val simpleDateFormat = SimpleDateFormat("yyyy-MM-dd")// HH:mm:ss
        //获取当前时间
        val day = Date(System.currentTimeMillis())
        today = simpleDateFormat.format(day)


        tv_month.text =
            mCalendarView.curYear.toString() + "年" + mCalendarView.curMonth.toString() + "月"
        tv_month_left.setOnClickListener(this)
        tv_month_right.setOnClickListener(this)
        currentMonth = mCalendarView.curYear.toString() + "-" + mCalendarView.curMonth
    }

    private var today = ""
    private var currentMonth = ""


    private fun requestData() {
        val params = RequestParams()
        params.put("month", currentMonth)
        params.put("token", ACache.get(Box.context).getAsString("token"))
        var url = Urls.HOST + "/education/teacher/course/getMonthCourseList"
        HttpUtil.post1(url, params, object : JsonHttpResponseHandler() {
            override fun onSuccess(
                statusCode: Int,
                headers: Array<out org.apache.http.Header>?,
                response: JSONObject?
            ) {
                super.onSuccess(statusCode, headers, response)
                stopRefresh()
                try {
                    if (response?.getString("code") == "0") {
                        println("课表返回=${response.getString("data")}")
                        var result = response.getString("data")
                        var data: List<Map<String, Object>> = ArrayList()
                        data = JsonMap.getList(result) as List<Map<String, Object>>
                        val map = HashMap<String, Calendar>()
                        for (obj in data) {
                            for (item in obj) {
                                var strs = item.key.split("-")
                                println("请求课表时间=" + strs + "###item.value=" + item.value)//2019-11-09
                                var year = strs[0].toInt()
                                var month = strs[1].toInt()
                                var day = strs[2].toInt()
                                var count = 0

                                var str = item.value.toString()
                                val jo: JSONObject = JSONObject(str)

                                /*  var jp=JsonParser()
                                  var dayBean=jp.parse(str)
                                  var obj=jp.parse(str).getAsJsonObject()*/
                                var csnum = jo.getInt("csnum")
                                var hdnum = jo.getInt("hdnum")
                                var tgnum = jo.getInt("tgnum")
                                var yxnum = jo.getInt("yxnum")

                                if (csnum > 0) {
                                    count += csnum
                                }
                                if (hdnum > 0) {
                                    count += hdnum
                                }
                                if (tgnum > 0) {
                                    count += tgnum
                                }
                                if (yxnum > 0) {
                                    count += yxnum
                                }
                                map[getSchemeCalendar(
                                    year,
                                    month,
                                    day,
                                    -0x20ecaa,
                                    count.toString()
                                ).toString()] =
                                    getSchemeCalendar(year, month, day, -0x20ecaa, count.toString())
                            }
                        }
                        //此方法在巨大的数据量上不影响遍历性能，推荐使用
                        mCalendarView.setSchemeDate(map)
                        requestDayData(today)
                    } else {
                        ShowToast("请求失败")

                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }


            override fun onFinish() {
                stopRefresh()
            }

            override fun onFailure(
                statusCode: Int,
                headers: Array<out org.apache.http.Header>?,
                responseString: String?,
                throwable: Throwable?
            ) {
                super.onFailure(statusCode, headers, responseString, throwable)
                stopRefresh()
            }
        })
        /* ApiClient.api.getMonthCourseList(UserCache.token, currentMonth)
             .compose(BaseResponseRx.validateToMain())
             ._subscribe {
                 _onNext {  it ->
                     stopRefresh()
                     println("###课表="+ it.size)
                     val map = HashMap<String, Calendar>()
 //                    var data: Map<String, CourseDayEntity>
                     var data: List<Map<String, DayEntity>> = ArrayList()
                     for (result in  it) {
                         println("###课表result="+  result.data)
                     }

                     //此方法在巨大的数据量上不影响遍历性能，推荐使用
                     mCalendarView.setSchemeDate(map)
                 }
                 _onError {
                     ShowToast(ErrorHandler.handle(it).errorMsg)
                     stopRefresh()
                 }
             }*/
    }


    private val dataList: MutableList<CourseDayEntity> = mutableListOf()

    //获取某天老师的课时安排表
    private fun requestDayData(day: String) {
        Alert.loading(self)
        ApiClient.api.getDayCourseList(UserCache.token, today)
            .compose(BaseResponseRx.validateToMain())
            ._subscribe {
                _onNext {
                    Alert.close()
                    stopRefresh()
                    dataList.clear()
                    if (dataList.size == 0) {
                        multiView.showEmpty()
                    }
                    if (it.size <= 0) {
                        smartLayout.setEnableLoadMore(false)
                    } else {
                        dataList.addAll(it)
                        proAdapter.notifyDataSetChanged()
                        multiView.showContent()
                    }
                }
                _onError {
                    Alert.close()
                    ShowToast(ErrorHandler.handle(it).errorMsg)
                    stopRefresh()
                }
            }
    }

    private fun stopRefresh() {
        if (smartLayout.state == RefreshState.Refreshing) {
            smartLayout.finishRefresh()
        } else if (smartLayout.state == RefreshState.Loading) {
            smartLayout.finishLoadMore(100)
        }
    }

    override fun onCalendarSelect(calendar: Calendar?, isClick: Boolean) {
        mYear = calendar?.getYear() ?: 2019
        today =
            calendar?.getYear().toString() + "-" + calendar?.getMonth().toString() + "-" + calendar?.getDay()
        tv_month.text = calendar?.year.toString() + "年" + calendar?.month.toString() + "月"
        println("###选择isClick=" + isClick + "" + today)//选择的月日=11月20日

        if (isClick) {
            //格式如2019-10-19
//            isRefreshing = true
            requestDayData(today)
        }

    }

    override fun onCalendarOutOfRange(calendar: Calendar?) {
    }


    override fun closeMvp() {
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.tv_month_left -> {
                mCalendarView.scrollToPre()//滚动到上一个月
                currentMonth = mCalendarView.curYear.toString() + "-" + mCalendarView.curMonth
                requestData()
            }
            R.id.tv_month_right -> {
                mCalendarView.scrollToNext()//滚动到下一个月
                currentMonth = mCalendarView.curYear.toString() + "-" + mCalendarView.curMonth
                requestData()
            }
        }

    }


    private fun getSchemeCalendar(
        year: Int,
        month: Int,
        day: Int,
        color: Int,
        text: String
    ): Calendar {
        val calendar = Calendar()
        calendar.year = year
        calendar.month = month
        calendar.day = day
        calendar.schemeColor = color//如果单独标记颜色、则会使用这个颜色
        calendar.scheme = text
        calendar.addScheme(Calendar.Scheme())
        calendar.addScheme(-0xff7800, "假")
        calendar.addScheme(-0xff7800, "节")
        return calendar
    }
}
